package cn.rkylin.oms.ectrade.service;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.rkylin.oms.ectrade.vo.UnpayQtyVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.ectrade.dao.IEcOrderDAO;
import cn.rkylin.oms.ectrade.dao.IEcTradeDAO;
import cn.rkylin.oms.ectrade.domain.EcOrder;
import cn.rkylin.oms.ectrade.domain.EcTrade;
import cn.rkylin.oms.ectrade.vo.EcOrderVO;
import cn.rkylin.oms.ectrade.vo.EcTradeVO;
import cn.rkylin.oms.refund.dao.IRefundDAO;
import cn.rkylin.oms.refund.dao.IRefundItemDAO;
import cn.rkylin.oms.refund.vo.EcRefundItemVO;
import cn.rkylin.oms.refund.vo.RefundVO;

/**
 * 订单管理服务实现
 * 
 * @author zhangheng
 * @version 1.0
 * @created 13-2月-2017 09:11:15
 */
@Service("ecTradeService")
public class EcTradeServiceImpl extends ApolloService implements IEcTradeService {

    @Resource(name = "redisTemplate")
    private RedisTemplate<Serializable, Serializable> redisTemplate;
    
    /**
     * 订单数据访问
     */
    @Autowired
    private IEcTradeDAO ecTradeDAO;
    
    /**
     * 订单数据访问
     */
    @Autowired
    private IEcOrderDAO ecOrderDAO;
    
    @Autowired
    private IRefundDAO ecRefundDAO;
    
    @Autowired
    private IRefundItemDAO ecRefundItemDAO;
    

    public IEcTradeDAO getEcTradeDAO() {
        return ecTradeDAO;
    }

    public void setEcTradeDAO(IEcTradeDAO ecTradeDAO) {
        this.ecTradeDAO = ecTradeDAO;
    }

    /**
     * 构造函数
     */
    public EcTradeServiceImpl() {
    }

    public PageInfo<EcTradeVO> findByWhere(int page, int rows, EcTradeVO ecorVO) throws Exception {
        PageInfo<EcTradeVO> ecoVOList = findPage(page, rows, "pageSelectEcTrade", ecorVO);
        return ecoVOList;
    }
    
    public PageInfo<EcTradeVO> findByWhereNew(int page, int rows, EcTradeVO ecorVO) throws Exception {
        PageInfo<EcTradeVO> ecoVOList = findPage(page, rows, "pageSelectEcTradeNew", ecorVO);
        return ecoVOList;
    }

    public List<EcTradeVO> findCounts(EcTradeVO ecTradeVO) throws Exception {
        List<EcTradeVO> list = findPage("selectEcTradeCounts", ecTradeVO);
        return list;
    }
    
    public List<EcTradeVO> findCountsNew(EcTradeVO ecTradeVO) throws Exception {
        List<EcTradeVO> list = findPage("selectEcTradeCountsNew", ecTradeVO);
        return list;
    }

    /**
     * 根据tid取得EcTrade
     *
     * @param ecTradeVO
     * @throws Exception
     */
    @Cacheable(value = "EcTradeVO", key = "T(String).valueOf('ecTrade:').concat(#ecTradeVO.shopId).concat(':').concat(#ecTradeVO.ecTradeCode)")
    public List<EcTradeVO> findByTid(EcTradeVO ecTradeVO) throws Exception {
        List<EcTradeVO> list = findPage("selectEcTradeByTid", ecTradeVO);
        return list;
    }

    public EcTradeVO getEcTradeById(String id) throws Exception {
        EcTradeVO vo = ecTradeDAO.findById(id);
        return vo;
    }

    /**
     * 订单打回
     */
    public Map<String, Object> rejectOrder(Map<String, String> requestParam) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String shopId = "";     //店铺id
        String tradeCode = "";  //交易号
        String itemCode = "";   //商品号
        String skuCode = "";    //规格号
      
        shopId = requestParam.get("shopId");
        tradeCode = requestParam.get("tradeCode");
        itemCode = requestParam.get("itemCode");
        skuCode = requestParam.get("skuCode");
        
        //根据店铺，交易号取得订单对象
        //调用数据层返回信息
        Map<String , String> tradeMap = new HashMap<String,String>();
        tradeMap.put("shopId", shopId);
        tradeMap.put("tradeCode", tradeCode.split("-")[0]);
        List<EcTradeVO> tradeList = ecTradeDAO.findTradeList("SelectTradeByTradeCode", tradeMap);
      
        //如果订单号不存的时候退出
        if (tradeList==null || tradeList.size()<=0){
            returnMap.put("success", "n");
            returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + " 的数据不存在");
            returnMap.put("errorNo", "303");
            return returnMap;
        }
      
        //定位订单数据
        EcTradeVO trade = null;
        EcTradeVO parentTrade = ecTradeDAO.findById(tradeList.get(0).getParentTradeId());
        for (int i = 0 ; i < tradeList.size() ; i++){
//            if (tradeCode.equals(tradeList.get(i).getEcTradeCode()) && "y".equals(tradeList.get(i).getSplitStatus())){
            if (!tradeList.get(i).getEcTradeId().equals(tradeList.get(i).getParentTradeId()) && "y".equals(tradeList.get(i).getSplitStatus())){
                trade = tradeList.get(i);
                break;
            }
        }
                
        //如果订单取得失败
        if(parentTrade==null){
            returnMap.put("success", "n");
            returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + " 的数据不存在");
            returnMap.put("errorNo", "301");
            return returnMap;
        }
        if (trade==null){
            returnMap.put("success", "n");
            returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + " 的数据不存在");
            returnMap.put("errorNo", "301");
            return returnMap;
        }
        
      //根据订单号，商品号，规格号取得order对象
      Map<String,String> map = new HashMap<String,String>();
      map.put("ecTradeId", trade.getEcTradeId());
//      map.put("ecItemCode", itemCode);
//      map.put("ecSkuCode", skuCode);
      List<EcOrderVO> listOrder = new ArrayList<EcOrderVO>();
      List<EcOrderVO> listOrderDeal = ecOrderDAO.findOrderList("selectOrderByTradeItemSku", map);      
      //TODO 暂时对原始的order不做修改
//      map.put("ecTradeId", parentTrade.getEcTradeId());
//      List<Order> listParentOrder = tradeDAO.findOrderList(DataSourceEnvironment.SLAVE, "selectOrderByTradeItemSku", map);
//      
      //如果Order不存的时候退出
      if (listOrderDeal==null || listOrderDeal.size() <= 0){
          returnMap.put("success", "n");
          returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + "  商品：" + itemCode + "  规格：" + skuCode + " 的数据不存在");
          returnMap.put("errorNo", "301");
          return returnMap;
      }
      
      for (int i = 0 ; i < listOrderDeal.size() ; i++){
          if (itemCode.equals(listOrderDeal.get(i).getEcItemCode()) && skuCode.equals(listOrderDeal.get(i).getEcSkuCode())){
              listOrder.add(listOrderDeal.get(i));
          }
      }
      //TODO 暂时对原始的order不做修改        
//      if (listParentOrder==null || listParentOrder.size() <= 0){
//          responseRejectOrder.setSuccess("n");
//          responseRejectOrder.setMsg("订单号："+tradeCode+"  店铺："+ shopId + "  商品：" + itemCode + "  规格：" + skuCode + " 的数据不存在");
//          responseRejectOrder.setCode("999");
//          return responseRejectOrder;
//      }
      
      Date date = new Date();
      //修改parent订单的数据
      parentTrade.setUpdateTime(date);
      parentTrade.setSplitStatus("n");
      EcTrade parentEcTrade = new EcTrade();
      BeanUtils.copyProperties(parentTrade, parentEcTrade);
      ecTradeDAO.update(parentEcTrade);
      
      
    //修改当前的订单数据
      EcTrade ecTrade = new EcTrade();
      trade.setUpdateTime(date);
      BeanUtils.copyProperties(trade, ecTrade);
      String id = java.util.UUID.randomUUID().toString().replaceAll("-", "");
      if (listOrder.size()!=listOrderDeal.size()){
          SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMddHHmmssSSS");
          ecTrade.setEcTradeCode(ecTrade.getEcTradeCode().split("-")[0]+"-"+formatter.format(new Date()));
          ecTrade.setEcTradeId(id);
          ecTrade.setSplitStatus("n");
          ecTradeDAO.insert(ecTrade);
      } else {
          id = ecTrade.getEcTradeId();
          ecTrade.setSplitStatus("n");
          ecTradeDAO.update(ecTrade);    
      }
      
      //修改当前的order数据
      for (int i = 0 ; i < listOrder.size() ; i++){
          EcOrder ecorder = new EcOrder();
          listOrder.get(i).setUpdateTime(date);
          listOrder.get(i).setDeleteReason("分单错误");
          listOrder.get(i).setErpStatus("已删除");
          BeanUtils.copyProperties(listOrder.get(i), ecorder);
          ecorder.setEcTradeId(id);
          ecOrderDAO.update(ecorder);
      }
      
      //TODO 暂时对原始的order不做修改        修改Parent的order数据
      
      //查看退款单数据
      Map<String , String> refundMap = new HashMap<String,String>();
      refundMap.put("tradeCode", tradeCode.split("-")[0]);
      refundMap.put("itemcode", itemCode);
      refundMap.put("skycode", skuCode);
      List<RefundVO> refundList = ecRefundDAO.findRefundList("SelectEcRefundByTradeCode", refundMap);
      
      if (refundList!=null && refundList.size()>0){
          RefundVO refundVO = null;
          RefundVO parentRefundVO = null;
          for (int i = 0 ; i < refundList.size() ; i++){
              if (refundList.get(i).getEcRefundId().equals(refundList.get(i).getParentRefundId())){
                  parentRefundVO = refundList.get(i);
              } else {
                  refundVO = refundList.get(i);
              }
              
//            Map<String,String> refundItemMap = new HashMap<String,String>();
//            refundItemMap.put("ecSkuCode", skuCode);
//            refundItemMap.put("ecRefundId", parentRefundVO.getEcRefundId());
//            refundItemMap.put("ecItemCode", itemCode);
//            List<EcRefundItemVO> listEcRefundItemVO = ecRefundItemDAO.findRefundItemList("selectByItemSkuEcRefundItem", map);
              if(parentRefundVO!=null){
                  parentRefundVO.setUpdateTime(date);
                  parentRefundVO.setSplitStatus("n");
                  parentRefundVO.setEcTradeCode(ecTrade.getEcTradeCode());
                  parentRefundVO.setErrDesc("分单错误");
                  parentRefundVO.setErpStatus("已删除");
                  ecRefundDAO.update(parentRefundVO);
              }
//            if (listEcRefundItemVO!=null  && listEcRefundItemVO.size() > 0) {
//                for (int i = 0 ; i < listEcRefundItemVO.size() ; i++){
//                    listEcRefundItemVO.get(i)
//                }
//            }
            
            //如果是分单的场合，还有分单数据
            if(refundVO!=null){
//                refundItemMap.put("ecSkuCode", skuCode);
//                refundItemMap.put("ecRefundId", refundVO.getEcRefundId());
//                refundItemMap.put("ecItemCode", itemCode);
//                listEcRefundItemVO = ecRefundItemDAO.findRefundItemList("selectByItemSkuEcRefundItem", map);
                refundVO.setUpdateTime(date);
                refundVO.setSplitStatus("n");
                refundVO.setErrDesc("分单错误");
                refundVO.setErpStatus("已删除");
                refundVO.setEcTradeCode(ecTrade.getEcTradeCode());
                ecRefundDAO.update(refundVO);
            }
            
            refundVO = null;
            parentRefundVO = null;
            
          }
          
      }

      returnMap.put("success", "y");
      returnMap.put("msg", "");
      returnMap.put("errorNo", "");
      return returnMap;
    }
    
    /**
     * 订单删除
     */
    public Map<String, Object> deleteOrder(Map<String, String> requestParam) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String shopId = "";     //店铺id
        String tradeCode = "";  //交易号
        String itemCode = "";   //商品号
        String skuCode = "";    //规格号
      
        shopId = requestParam.get("shopId");
        tradeCode = requestParam.get("tradeCode");
        itemCode = requestParam.get("itemCode");
        skuCode = requestParam.get("skuCode");
        
        //根据店铺，交易号取得订单对象
        //调用数据层返回信息
        Map<String , String> tradeMap = new HashMap<String,String>();
        tradeMap.put("shopId", shopId);
        tradeMap.put("tradeCode", tradeCode.split("-")[0]);
        List<EcTradeVO> tradeList = ecTradeDAO.findTradeList("SelectTradeByTradeCode", tradeMap);
      
        //如果订单号不存的时候退出
        if (tradeList==null || tradeList.size()<=0){
            returnMap.put("success", "n");
            returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + " 的数据不存在");
            return returnMap;
        }
      
        //定位订单数据
      //定位订单数据
        EcTradeVO trade = null;
        EcTradeVO parentTrade = ecTradeDAO.findById(tradeList.get(0).getParentTradeId());
        for (int i = 0 ; i < tradeList.size() ; i++){
            if (tradeCode.equals(tradeList.get(i).getEcTradeCode())){
                trade = tradeList.get(i);
                break;
            }
        }
                
        //如果订单取得失败
        if(parentTrade==null){
            returnMap.put("success", "n");
            returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + " 的数据不存在");
            return returnMap;
        }
        if (trade==null){
            returnMap.put("success", "n");
            returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + " 的数据不存在");
            return returnMap;
        }
        
      //根据订单号，商品号，规格号取得order对象
      Map<String,String> map = new HashMap<String,String>();
      map.put("ecTradeId", trade.getEcTradeId());
//      map.put("ecItemCode", itemCode);
//      map.put("ecSkuCode", skuCode);
      List<EcOrderVO> listOrder = new ArrayList<EcOrderVO>();
      List<EcOrderVO> listOrderDeal = ecOrderDAO.findOrderList("selectOrderByTradeItemSku", map);
      //TODO 暂时对原始的order不做修改
//      map.put("ecTradeId", parentTrade.getEcTradeId());
//      List<Order> listParentOrder = tradeDAO.findOrderList(DataSourceEnvironment.SLAVE, "selectOrderByTradeItemSku", map);
//      
      //如果Order不存的时候退出
      if (listOrderDeal==null || listOrderDeal.size() <= 0){
          returnMap.put("success", "n");
          returnMap.put("msg", "订单号："+tradeCode+"  店铺："+ shopId + "  商品：" + itemCode + "  规格：" + skuCode + " 的数据不存在");
          return returnMap;
      }
      
      for (int i = 0 ; i < listOrderDeal.size() ; i++){
          if (itemCode.equals(listOrderDeal.get(i).getEcItemCode()) && skuCode.equals(listOrderDeal.get(i).getEcSkuCode())){
              listOrder.add(listOrderDeal.get(i));
          }
      }
      //TODO 暂时对原始的order不做修改        
//      if (listParentOrder==null || listParentOrder.size() <= 0){
//          responseRejectOrder.setSuccess("n");
//          responseRejectOrder.setMsg("订单号："+tradeCode+"  店铺："+ shopId + "  商品：" + itemCode + "  规格：" + skuCode + " 的数据不存在");
//          responseRejectOrder.setCode("999");
//          return responseRejectOrder;
//      }
      
      Date date = new Date();
      //修改parent订单的数据
//      parentTrade.setUpdateTime(date);
      EcTrade parentEcTrade = new EcTrade();
      BeanUtils.copyProperties(parentTrade, parentEcTrade);
      ecTradeDAO.update(parentEcTrade);
      
      
      //修改当前的订单数据
      EcTrade ecTrade = new EcTrade();
//      trade.setUpdateTime(date);
      BeanUtils.copyProperties(trade, ecTrade);
      String id = java.util.UUID.randomUUID().toString().replaceAll("-", "");
//      if (listOrder.size()!=listOrderDeal.size()){
////          SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMddHHmmssSSS");
////          ecTrade.setEcTradeCode(ecTrade.getEcTradeCode().split("-")[0]+"-"+formatter.format(new Date()));
//          ecTrade.setEcTradeId(id);
//          ecTrade.setSplitStatus("n");
//          ecTradeDAO.insert(ecTrade);
//      } else {
          id = ecTrade.getEcTradeId();
//          ecTrade.setSplitStatus("n");
          ecTradeDAO.update(ecTrade);    
//      }
      
      //修改当前的order数据
      for (int i = 0 ; i < listOrder.size() ; i++){
          EcOrder ecorder = new EcOrder();
//          listOrder.get(i).setUpdateTime(date);
          listOrder.get(i).setErpStatus("已删除");
          BeanUtils.copyProperties(listOrder.get(i), ecorder);
          ecorder.setEcTradeId(id);
          ecOrderDAO.update(ecorder);
      }
      
      //TODO 暂时对原始的order不做修改        修改Parent的order数据
      
      returnMap.put("success", "y");
      returnMap.put("msg","");
      return returnMap;
    }

    /**
     * 获取未付款数
     *
     * @param shopId
     * @param skuId
     * @return
     * @throws Exception
     */
    @Override
    public int getUnpayQty(String shopId, String skuId) throws Exception {
        UnpayQtyVO para = new UnpayQtyVO();
        para.setShopId(shopId);
        para.setSkuId(skuId);
        UnpayQtyVO unpayQtyVO = ecTradeDAO.getUnpayQty(para);
        if(unpayQtyVO != null){
            return unpayQtyVO.getUnpayQty();
        }
        else{
            return 0 ;
        }
    }
}
